Completed
Push — master ( 2115c9...bdfcbe )
by
unknown
02:14
created

template.js ➔ ... ➔ ???   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
nc 1
dl 0
loc 8
rs 9.4285
c 1
b 0
f 0
nop 1
1
import fse from 'fs-extra'
2
import {Promise} from 'es6-promise'
3
import path from 'path'
4
import {
5
  getAttr
6
  ,Util
7
  ,config
8
  ,fileUtils
9
  ,cmsData
10
  ,escapeTextToRegex
11
  ,Hooks
12
} from '../../'
13
14
export function findTemplateAndPartialsInFolder (currentPath) {
15
  var res = []
16
  var files = fse.readdirSync(currentPath)
17
  for (var i in files) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
18
    var currentFile = currentPath + '/' + files[i]
19
    var stats = fse.statSync(currentFile)
20
    if (stats.isFile()) {
21
      if (currentFile.indexOf('.' + config.files.templates.extension) > -1) {
22
        res.push(currentFile)
23
      }
24
    }
25
    else if (stats.isDirectory()) {
26
      res = res.concat(findTemplateAndPartialsInFolder(currentFile))
27
    }
28
  }
29
  return res
30
}
31
32
export function getTemplateAndPartials(templatesPath) {
33
  var p = new Promise((resolve) => {
34
    let templatesList = findTemplateAndPartialsInFolder(templatesPath)
35
    resolve(templatesList)
36
  })
37
38
  return p
39
}
40
41
export function addOrder(text) {
42
  var regAbe = /{{abe[\S\s].*?key=['|"]([\S\s].*?['|"| ]}})/g
43
  var matches = text.match(regAbe)
44
  var order = 0
45
  
46
  if(typeof matches !== 'undefined' && matches !== null){
47
    Array.prototype.forEach.call(matches, (match) => {
48
      if(typeof match !== 'undefined' && match !== null) {
49
        
50
        var orderAttr = getAttr(match, 'order')
51
52
        if(typeof orderAttr === 'undefined' || orderAttr === null || orderAttr === '') {
53
          var matchOrder = match.replace(/\}\}$/, ` order='${order}'}}`)
54
          text = text.replace(match, matchOrder)
55
        }
56
        order++
57
      }
58
    })
59
  }
60
  return text
61
}
62
63
export function getAbeImport(text) {
64
  var partials = []
65
  let listReg = /({{abe.*?type=[\'|\"]import.*?}})/g
66
  var match
67
  while (match = listReg.exec(text)) {
68
    partials.push(match[0])
69
  }
70
71
  return partials
72
}
73
74
export function includePartials(text) {
75
  var abeImports = getAbeImport(text)
76
77
  Array.prototype.forEach.call(abeImports, (abeImport) => {
78
    var obj = Util.getAllAttributes(abeImport, {})
79
80
    var file = obj.file
81
    var partial = ''
82
    file = path.join(config.root, config.partials, file)
83
    if(fileUtils.isFile(file)) {
84
      partial = includePartials(fse.readFileSync(file, 'utf8'))
85
    }
86
    text = text.replace(escapeTextToRegex(abeImport, 'g'), partial)
87
  })
88
89
  return text
90
}
91
92
function translate(text) {
93
  var importReg = /({{abe.*type=[\'|\"]translate.*}})/g
94
95
  var matches = text.match(importReg)
96
  
97
  if(typeof matches !== 'undefined' && matches !== null) {
98
    Array.prototype.forEach.call(matches, (match) => {
99
      var splitedMatches = match.split('{{abe ')
100
101
      Array.prototype.forEach.call(splitedMatches, (splitedMatch) => {
102
        var currentMatch = `{{abe ${splitedMatch}`
103
        if(/({{abe.*type=[\'|\"]translate.*}})/.test(currentMatch)) {
104
          var locale = getAttr(currentMatch, 'locale')
105
          var source = getAttr(currentMatch, 'source')
106
107
          if (locale.indexOf('{{') === -1) {
108
            locale = `'${locale}'`
109
          }else {
110
            locale = locale.replace(/\{\{(.*?)\}\}/, '$1')
111
          }
112
113
          if (source.indexOf('{{') === -1) {
114
            source = `'${source.replace(/'/g, '\\\'')}'`
115
          }else {
116
            source = source.replace(/\{\{(.*?)\}\}/, '$1')
117
          }
118
119
          // var replace = `{{{i18nAbe ${locale} ${source}}}}`
120
          var replace = currentMatch.replace('{{abe', '{{i18nAbe')
121
          replace = replace.replace(/locale=['|"].*?['|"]/, locale)
122
          replace = replace.replace(/source=['|"].*?['|"]/, source)
123
          replace = replace.replace(/{{i18nAbe.*?}}/, `{{{i18nAbe ${locale} ${source}}}}`)
124
125
          text = text.replace(escapeTextToRegex(currentMatch, 'g'), replace)
126
        }
127
      })
128
    })
129
  }
130
131
  return text
132
}
133
134
export function getTemplate (file) {
135
  var text = ''
136
137
  // HOOKS beforeGetTemplate
138
  file = Hooks.instance.trigger('beforeGetTemplate', file)
139
140
  file = file.replace(path.join(config.root, config.templates.url), '')
141
  file = file.replace(config.root, '')
142
  if (file.indexOf('.') > -1) {
143
    file = fileUtils.removeExtension(file)
144
  }
145
  file = path.join(config.root, config.templates.url, file + '.' + config.files.templates.extension)
146
  if(fileUtils.isFile(file)) {
147
    text = fse.readFileSync(file, 'utf8')
148
    text = includePartials(text)
149
    text = translate(text)
150
    text = addOrder(text)
151
  }else {
152
    text = `[ ERROR ] template ${config.templates.url} doesn't exist anymore`
153
  }
154
155
  // HOOKS afterGetTemplate
156
  text = Hooks.instance.trigger('afterGetTemplate', text)
157
158
  return text
159
}
160
161
export function getVariablesInWhere(where) {
162
  var ar = []
163
164
  if(where.left.column.indexOf('{{') > -1) {
165
    ar.push(where.left.column.replace(/\{\{(.*?)\}\}/, '$1'))
166
  }
167
  else{
168
    ar.push(where.left.column)
169
  }
170
171
  if (where.right.value) {
172
    if (typeof where.right.value === 'string') {
173
      if(where.right.value && where.right.value.indexOf('{{') > -1) {
174
        ar.push(where.right.value.replace(/\{\{(.*?)\}\}/, '$1'))
175
      }
176
    }else {
177
      where.right.value.forEach(function (value) {
178
        if(value.column.indexOf('{{') > -1) {
179
          ar.push(value.column.replace(/\{\{(.*?)\}\}/, '$1'))
180
        }
181
      })
182
    }
183
  }
184
185
  if(where.right.column && where.right.column.indexOf('{{') > -1) {
186
    ar.push(where.right.column.replace(/\{\{(.*?)\}\}/, '$1'))
187
  }
188
189
  return ar
190
}
191
192
/**
193
 * Get columns and where.left ids of a select statement
194
 *
195
 * select title, image from ../ where template=""
196
 *
197
 * return [title, image, template]
198
 * 
199
 * @param  {Array} templatesList ["article.html", "other.html"]
0 ignored issues
show
Documentation introduced by
The parameter templatesList does not exist. Did you maybe forget to remove this comment?
Loading history...
200
 * @return {Promise}
201
 */
202
export function recurseWhereVariables (where) {
203
  var ar = []
0 ignored issues
show
Unused Code introduced by
The assignment to variable ar seems to be never used. Consider removing it.
Loading history...
204
  var arLeft
205
  var arRight
206
  switch(where.operator) {
207
  case 'AND':
208
    arLeft = recurseWhereVariables(where.left)
209
    arRight = recurseWhereVariables(where.right)
210
    return arLeft.concat(arRight)
211
    break
0 ignored issues
show
Unused Code introduced by
This break statement is unnecessary and may be removed.
Loading history...
212
  case 'OR':
213
    arLeft = recurseWhereVariables(where.left)
214
    arRight = recurseWhereVariables(where.right)
215
    return arLeft.concat(arRight)
216
    break
0 ignored issues
show
Unused Code introduced by
This break statement is unnecessary and may be removed.
Loading history...
217
  default:
218
    ar = getVariablesInWhere(where)
219
    break
220
  }
221
222
  return ar
223
}
224
225
export function execRequestColumns(tpl) {
226
  let util = new Util()
227
  var ar = []
228
  var matches = util.dataRequest(tpl)
229
  Array.prototype.forEach.call(matches, (match) => {
230
    var obj = Util.getAllAttributes(match[0], {})
231
    var type = cmsData.sql.getSourceType(obj.sourceString)
232
    switch (type) {
0 ignored issues
show
Coding Style introduced by
As per coding-style, switch statements should have a default case.
Loading history...
233
    case 'request':
234
      var request = cmsData.sql.handleSqlRequest(obj.sourceString, {})
235
      if(typeof request.columns !== 'undefined' && request.columns !== null) {
236
        Array.prototype.forEach.call(request.columns, (column) => {
237
          ar.push(column)
238
        })
239
      }
240
      if(typeof request.where !== 'undefined' && request.where !== null) {
241
        ar = ar.concat(recurseWhereVariables(request.where))
242
      }
243
    }
244
  })
245
246
  return ar
247
}
248
249
export function findRequestColumns(templatesList) {
250
  var whereKeys = []
251
  var p = new Promise((resolve) => {
252
    Array.prototype.forEach.call(templatesList, (file) => {
253
      var template = fse.readFileSync(file, 'utf8')
254
      whereKeys = whereKeys.concat(execRequestColumns(template))
255
    })
256
    whereKeys = whereKeys.filter(function (item, pos) {return whereKeys.indexOf(item) == pos})
257
    resolve(whereKeys)
258
  })
259
260
  return p
261
}
262
263
export function getSelectTemplateKeys(templatesPath) {
264
  var p = new Promise((resolve, reject) => {
265
    getTemplateAndPartials(templatesPath)
266
      .then((templatesList) => {
267
        findRequestColumns(templatesList)
268
          .then((whereKeys) => {
269
            resolve(whereKeys)
270
          },
271
          () => {
272
            console.log('findRequestColumns reject')
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
273
            reject()
274
          })
275
          .catch((e) => {
276
            console.error('getSelectTemplateKeys', e)
277
            reject()
278
          })
279
      },
280
      () => {
281
        console.log('getTemplateAndPartials reject')
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
282
        reject()
283
      })
284
      .catch((e) => {
285
        console.error('getSelectTemplateKeys', e)
286
        reject()
287
      })
288
289
  })
290
291
  return p
292
}